//
//  TabBarViewController.m
//  SmartCup
//
//  Created by Kendama on 2017/5/16.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "TabBarViewController.h"
#import "MyViewController.h"
#import "HomeViewController.h"
#import "FindViewController.h"
#import "ContactsViewController.h"
#import "ChatViewController.h"
#import <UserNotifications/UserNotifications.h>
#import "DemoConfManager.h"
#import "PushNoticeApi.h"
#import "DataManager.h"
#import "NewMessageModel.h"

//两次提示的默认间隔
static const CGFloat kDefaultPlaySoundInterval = 3.0;
static NSString *kMessageType = @"MessageType";
static NSString *kConversationChatter = @"ConversationChatter";
static NSString *kGroupName = @"GroupName";

@interface TabBarViewController ()<UIAlertViewDelegate, EMCallManagerDelegate>

@end

@implementation TabBarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setTabBarItem];

    [[UITabBar appearance] setShadowImage:[UIImage new]];
    [[UITabBar appearance] setBackgroundImage:[[UIImage alloc]init]];
    
    [DemoConfManager sharedManager].mainController = self;

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNewMessage:) name:HuanXinNewMessage object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)receiveNewMessage:(NSNotification *)notification
{
//    NSDictionary *dict = notification.userInfo;
    
//    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
//    NSInteger unreadCount = 0;
//    for (EMConversation *conversation in conversations) {
//        unreadCount += conversation.unreadMessagesCount;
//    }
    NSArray *array = [NewMessageModel selectFromClassAllObject];
    NSInteger unreadCount = array.count;
    UITabBarItem *item = [self.tabBar.items objectAtIndex:1];
    if (unreadCount > 0) {
        item.badgeValue = [NSString stringWithFormat:@"%i",(int)unreadCount];
    }else{
        item.badgeValue = nil;
    }
//    UITabBarItem *item = [self.tabBar.items objectAtIndex:1];
//    if ([EXRACT_OBJECT(DEVICEID) isEqualToString:@"0"] || !EXRACT_OBJECT(DEVICEID)) // 没有设备
//    {
//
//    }
//    else
//    {
//        item.badgeValue = @"1";
//    }
}

- (void)didClickPowerButton
{
//    NSDictionary *dict = @{@"code":@"1001",@"data":@{@"album_id":@"2677685",@"index":@"1"}};
//    [[DataManager sharedInstance] sendCode:@"1001" data:@{@"album_id":@"2677685",@"index":@"1"}];
    

//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        PushNoticeApi *api = [[PushNoticeApi alloc] initWithDic:@{@"sn":@"0123456789abcdef",@"title":@"报警",@"content":@"提醒你喝水了"}];
        [api dtStartYTKRequestCompletionBlockWithSuccess:^(YTKBaseRequest * _Nonnull request) {

        } failure:^(YTKBaseRequest * _Nonnull request) {

        }];
//    });
    
//    [self sendCode:@"1001" data:@{@"album_id":@"2677685",@"index":@"1"}];

}


- (void)setTabBarItem
{
    
    HomeViewController *homeVC = [[HomeViewController alloc] init];
    homeVC.tabBarItem.title = @"主页";
    homeVC.navigationItem.title = @"主页";
    
    ContactsViewController *chatVC = [[ContactsViewController alloc] init];
    chatVC.tabBarItem.title = @"聊天";
    chatVC.navigationItem.title = @"聊天";
    
    UIViewController *emptyVC = [[UIViewController alloc] init];
    emptyVC.tabBarItem.title = @"";
    emptyVC.tabBarItem.enabled = NO;
    emptyVC.navigationItem.title = @"";
    
    FindViewController *findVC = [[FindViewController alloc] init];
    findVC.tabBarItem.title = @"发现";
    findVC.navigationItem.title = @"发现";
    
    MyViewController *myVC = [[MyViewController alloc] init];
    myVC.tabBarItem.title = @"我的";
    myVC.navigationItem.title = @"我的";
    
    self.viewControllers = @[[self giveMeNavWithVC:homeVC andImgName:@"tab_home" andSelectedImgName:@"tab_home_pre"],
                             [self giveMeNavWithVC:chatVC andImgName:@"tab_chat" andSelectedImgName:@"tab_chat_pre"],
                             [self giveMeNavWithVC:emptyVC andImgName:@"" andSelectedImgName:@""],
                             [self giveMeNavWithVC:findVC andImgName:@"tab_find" andSelectedImgName:@"tab_find_pre"],
                             [self giveMeNavWithVC:myVC andImgName:@"tab_my" andSelectedImgName:@"tab_my_pre"]
                            ];

    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/2-37.5 , -20, 75, 75)];
    button.layer.masksToBounds = YES;
//    [button setBackgroundColor:[UIColor whiteColor]];
//    button.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [button setImage:[UIImage imageNamed:@"tab_power"] forState:UIControlStateNormal];
    [self.tabBar addSubview:button];
//    self.tabBar.autoresizingMask =UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleBottomMargin|UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin;
//    [button mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.bottom.mas_equalTo(self.tabBar.mas_bottom);
//        make.height.width.mas_equalTo(75);
//        make.centerX.mas_equalTo(0);
//    }];
    [self.tabBar bringSubviewToFront:button];
    [button addTarget:self action:@selector(didClickPowerButton) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.tabBar.backgroundColor = rgba(48,70,118,1);
    
    
}

- (UIViewController *)giveMeVC:(UIViewController *)VC andImgName:(NSString *)imgName andSelectedImgName:(NSString *)selImgName
{
    //    nav.tabBarItem = [[UITabBarItem alloc] initWithTitle:VC.tabBarItem.title image:[self removeRendering:imgName] tag:0];
    VC.tabBarItem = [[UITabBarItem alloc] initWithTitle:VC.tabBarItem.title image:[self removeRendering:imgName] selectedImage:[self removeRendering:selImgName]];
    
    [VC.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:rgba(187,192,203,1)}
                                  forState:UIControlStateNormal];
    [VC.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:rgba(0,159,236,1)} forState:UIControlStateHighlighted];
    return VC;
}


/**
 *  快速创建Nav
 */
- (UINavigationController *)giveMeNavWithVC:(UIViewController *)VC andImgName:(NSString *)imgName andSelectedImgName:(NSString *)selImgName
{
    UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:VC];
//    nav.tabBarItem = [[UITabBarItem alloc] initWithTitle:VC.tabBarItem.title image:[self removeRendering:imgName] tag:0];
    nav.tabBarItem = [[UITabBarItem alloc] initWithTitle:VC.tabBarItem.title image:[self removeRendering:imgName] selectedImage:[self removeRendering:selImgName]];
    [nav.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:rgba(187,192,203,1)}
                                  forState:UIControlStateNormal];
    [nav.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:rgba(0,159,236,1)} forState:UIControlStateHighlighted];

    return nav;
}


/**
 *  返回取消渲染的image
 */
- (UIImage *)removeRendering:(NSString *)imageName
{
    UIImage * image = [UIImage imageNamed:imageName];
    return [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}


- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    item.badgeValue = nil;
}


- (void)jumpToChatList
{
    if ([self.navigationController.topViewController isKindOfClass:[ChatViewController class]]) {
        //        ChatViewController *chatController = (ChatViewController *)self.navigationController.topViewController;
        //        [chatController hideImagePicker];
    }
//    else if(_chatListVC)
//    {
//        [self.navigationController popToViewController:self animated:NO];
//        [self setSelectedViewController:_chatListVC];
//    }
}



- (void)didReceiveLocalNotification:(UILocalNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    if (userInfo)
    {
        if ([self.navigationController.topViewController isKindOfClass:[ChatViewController class]]) {
            //            ChatViewController *chatController = (ChatViewController *)self.navigationController.topViewController;
            //            [chatController hideImagePicker];
        }
        
        NSArray *viewControllers = self.navigationController.viewControllers;
        [viewControllers enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop){
            if (obj != self)
            {
                if (![obj isKindOfClass:[ChatViewController class]])
                {
                    [self.navigationController popViewControllerAnimated:NO];
                }
                else
                {
                    NSString *conversationChatter = userInfo[kConversationChatter];
                    ChatViewController *chatViewController = (ChatViewController *)obj;
                    if (![chatViewController.conversation.conversationId isEqualToString:conversationChatter])
                    {
                        [self.navigationController popViewControllerAnimated:NO];
                        EMChatType messageType = [userInfo[kMessageType] intValue];
#ifdef REDPACKET_AVALABLE
                        chatViewController = [[RedPacketChatViewController alloc] initWithConversationChatter:conversationChatter conversationType:[self conversationTypeFromMessageType:messageType]];
#else
                        chatViewController = [[ChatViewController alloc] initWithConversationChatter:conversationChatter conversationType:[self conversationTypeFromMessageType:messageType]];
#endif
                        [self.navigationController pushViewController:chatViewController animated:NO];
                    }
                    *stop= YES;
                }
            }
            else
            {
                ChatViewController *chatViewController = nil;
                NSString *conversationChatter = userInfo[kConversationChatter];
                EMChatType messageType = [userInfo[kMessageType] intValue];
#ifdef REDPACKET_AVALABLE
                chatViewController = [[RedPacketChatViewController alloc] initWithConversationChatter:conversationChatter conversationType:[self conversationTypeFromMessageType:messageType]];
#else
                chatViewController = [[ChatViewController alloc] initWithConversationChatter:conversationChatter conversationType:[self conversationTypeFromMessageType:messageType]];
#endif
                [self.navigationController pushViewController:chatViewController animated:NO];
            }
        }];
    }
//    else if (_chatListVC)
//    {
//        [self.navigationController popToViewController:self animated:NO];
//        [self setSelectedViewController:_chatListVC];
//    }
}

- (EMConversationType)conversationTypeFromMessageType:(EMChatType)type
{
    EMConversationType conversatinType = EMConversationTypeChat;
    switch (type) {
        case EMChatTypeChat:
            conversatinType = EMConversationTypeChat;
            break;
        case EMChatTypeGroupChat:
            conversatinType = EMConversationTypeGroupChat;
            break;
        case EMChatTypeChatRoom:
            conversatinType = EMConversationTypeChatRoom;
            break;
        default:
            break;
    }
    return conversatinType;
}

@end
